package com.upsuns.client;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.rmi.Naming;
import java.rmi.NotBoundException;

import com.upsuns.service.FileService;

/**
 *@Description:<p>RMI客户端，负责获取远程对象，拉取服务端文件</p>
 *@author 王旭
 *@time 2016年3月14日 下午10:50:31
 */
public class Client {
	
	private FileService fileService;
	
	private RandomAccessFile raf;
	
	private String host;
	
	private String savePath;
	
	public Client() {}
	
	public void doClient() throws NotBoundException, IOException {
		fileService = (FileService) Naming.lookup("rmi://"+host+":8888/file");
		
		System.out.println("绑定成功...");
		
		System.out.println("文件名：" + fileService.getFileName());
		
		raf = new RandomAccessFile(new File(this.savePath+fileService.getFileName()), "rw");
		
		raf.setLength(fileService.getFileSize());
		
		FileChannel fileChannel = raf.getChannel();
		
		System.out.println("开始写文件...");
		
		//写入文件
		for(int times=1; times<=fileService.getTimes(); times++) {
			byte[] buffer = fileService.readFile(times);
			
			ByteBuffer byteBuffer = ByteBuffer.allocate(buffer.length);
			byteBuffer.put(buffer);
			byteBuffer.flip();
			
			fileChannel.write(byteBuffer, (long)(times-1)*fileService.getPerSize());
		}
		fileService.finished();
		System.out.println("文件接收成功");
	}
	
	/**
	 * 设置文件路径
	 * @param path
	 */
	public void setSavePath(String path) {
		this.savePath = path + "/";
	}
	
	/**
	 * 绑定远程对象主机
	 * @param host
	 */
	public void bind(String host) {
		this.host = host;
	}

}
